package com.nobuyme.box.xunfei;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.util.Log;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import org.xmlpull.v1.XmlSerializer;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;


public class Utils {

    /**
     * 检测网络是否可用
     *
     * @return
     */
    public static boolean isNetworkConnected(Context ctx) {
        ConnectivityManager cm = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo[] networkInfos = cm.getAllNetworkInfo();
        if (networkInfos != null && networkInfos.length > 0) {
            for (NetworkInfo tNetWorkInfo : networkInfos) {
                // 判断当前网络状态是否为连接状态
                if (tNetWorkInfo.getState() == NetworkInfo.State.CONNECTED) {
                    return true;
                }
            }
        }
        return false;
    }


    // BKDR Hash Function
    public static int BKDRHash(byte[] array) {
        int seed = 131; // 31 131 1313 13131 131313 etc..
        int hash = 0;

        for (int i = 0; i < array.length; i++) {
            hash = hash * seed + array[i];
        }

        return (hash & 0x7FFFFFFF);
    }


    /**
     * 將assets文件夹下的数据库拷贝到"/data/data/包名/databases/"目录下
     *
     * @param context
     * @param dbName  数据库名
     */
    public static void copyAssetsFile(Context context, String dbName) {
        OutputStream output = null;
        InputStream inStream = null;
        byte buffer[];
        String path = getIntechStorageDir(context) + "/databases/";
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File file = new File(path + dbName);
        try {
            inStream = context.getAssets().open(dbName);
            output = new FileOutputStream(file);
            buffer = new byte[4 * 1024];
            while ((inStream.read(buffer)) != -1) {
                output.write(buffer);
            }
            output.flush();
        } catch (MalformedURLException e) {
        } catch (ProtocolException e) {
        } catch (IOException e) {
        } finally {
            buffer = null;
            try {
                output.close();
            } catch (Exception e) {
            }
            try {
                inStream.close();
            } catch (Exception e) {
            }
        }
    }

    public static String getIntechStorageDir(Context context) {
        String state = Environment.getExternalStorageState();
        boolean imcc_dir_exist = false;
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + "bookrack");
            if (!file.exists()) {
                if (file.mkdir())
                    imcc_dir_exist = true;
                else
                    imcc_dir_exist = false;
            } else {
                imcc_dir_exist = true;
            }
        }

        if (imcc_dir_exist) {
            return Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + "bookrack";
        } else {
            return Environment.getDataDirectory().getAbsolutePath() + "/data" + "/" + context.getPackageName();
        }
    }

    /**
     * 获得不重复的字符串
     */
    public static String getUUID() {
        UUID uuid = UUID.randomUUID();
        return uuid.toString().toUpperCase().replace("-", "");
    }

    /**
     * 將字符串存储在xml文件中
     *
     * @param context
     * @param key
     * @param value
     */
    public static void saveConfig(Context context, String key, String value) {
        String path = Utils.getIntechStorageDir(context) + "/config";
        File dir = new File(path);
        if (!dir.exists() && !dir.mkdir()) {
            return;
        }

        File file = new File(path + "/" + key);
        try {
            if (!file.exists() && !file.createNewFile()) {
                return;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            FileWriter fileWriter = new FileWriter(file);
            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            factory.setNamespaceAware(true);
            XmlSerializer xmlSerializer = factory.newSerializer();
            xmlSerializer.setOutput(fileWriter);
            xmlSerializer.startDocument("utf-8", true);
            xmlSerializer.startTag(null, key);
            xmlSerializer.text(value);
            xmlSerializer.endTag(null, key);
            xmlSerializer.endDocument();
            fileWriter.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 从xml文件中解析key对应的字符串
     *
     * @param context
     * @param key
     * @return
     */
    public static String getConfig(Context context, String key) {
        String path = Utils.getIntechStorageDir(context) + "/config";
        File dir = new File(path);
        if (!dir.exists() && !dir.mkdir()) {
            return "";
        }

        File file = new File(path + "/" + key);
        if (!file.exists())
            return "";

        String value = "";
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(file);
            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            factory.setNamespaceAware(true);
            XmlPullParser parser = factory.newPullParser();
            parser.setInput(fileInputStream, "utf-8");
            int event = parser.getEventType();
            while (event != XmlPullParser.END_DOCUMENT) {
                if (event == XmlPullParser.START_TAG) {
                    String name = parser.getName();
                    if (name.equals(key)) {
                        if (parser.next() == XmlPullParser.TEXT) {
                            value = parser.getText();
                            break;
                        }
                    }
                }
                event = parser.next();
            }
            fileInputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return value;
    }

    public static String getHost(Context context) {
        return getConfig(context, "host", "manage.insyte.cn");
    }

    /**
     * 从xml文件中解析key对应的字符串
     *
     * @param context
     * @param key
     * @return
     */
    public static String getConfig(Context context, String key, String defaultValue) {
        String value = defaultValue;
        String path = Utils.getIntechStorageDir(context) + "/config";
        File dir = new File(path);
        if (!dir.exists() && !dir.mkdir()) {
            return value;
        }

        File file = new File(path + "/" + key);
        if (!file.exists())
            return value;

        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(file);
            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            factory.setNamespaceAware(true);
            XmlPullParser parser = factory.newPullParser();
            parser.setInput(fileInputStream, "utf-8");
            int event = parser.getEventType();
            while (event != XmlPullParser.END_DOCUMENT) {
                if (event == XmlPullParser.START_TAG) {
                    String name = parser.getName();
                    if (name.equals(key)) {
                        if (parser.next() == XmlPullParser.TEXT) {
                            value = parser.getText();
                            break;
                        }
                    }
                }
                event = parser.next();
            }
            fileInputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return value;
    }

    /**
     * MD5加密
     *
     * @return
     * @params
     */
    public static String md5(String s) {
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            digest.update(s.getBytes());
            byte messageDigest[] = digest.digest();
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < messageDigest.length; i++) {
                int val = ((int) messageDigest[i]) & 0xff;
                if (val < 16) {
                    hexString.append("0");
                }
                hexString.append(Integer.toHexString(val));
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            return s;
        }
    }

    /**
     * 保存用户的行为信息
     * @param ctx
     * @param str
     */
    final static String ACTION_NAME = "action";
//    public static void saveActionInfo(Context ctx, String str){
////        saveInfo(ctx,
////                "VersionCode:" + Utils.getVersionCode(ctx)
////                        + ";    VersionName:" + Utils.getVersionName(ctx)
////                +"Time: " + Utils.getDate() + ":" + str + "\r\n", "actionLog");
//
//        FileOutputStream fos = null;
//        try {
//            String path = Utils.getIntechStorageDir(ctx) + "/" + ACTION_NAME;
//            File file = new File(path + "/" + ACTION_NAME);
//            if (!file.exists())
//                file.mkdirs();
//            StringBuffer stringBuffer = new StringBuffer();
//            stringBuffer
//                    .append("VersionCode:" + Utils.getVersionCode(ctx))
//                    .append("---VersionName:" + Utils.getVersionName(ctx))
//                    .append("---Timer:")
//                    .append(Utils.getDate())
//                    .append(":")
//                    .append(str)
//                    .append("\r\n");
//            //TODO 修改最大的文件目录
//            scanVideoFile(file.getAbsolutePath(), 1024*30);
//            File actionFile = new File(file.getAbsolutePath() + "/" + Utils.getDate2());
//            if (actionFile.exists() == false)
//                actionFile.createNewFile();
//            fos = new FileOutputStream(actionFile, true);
//            fos.write((stringBuffer.toString()).getBytes());
//            fos.flush();
//        } catch (Exception e) {
//        } finally {
//            if (fos != null) {
//                try {
//                    fos.close();
//                    fos = null;
//                } catch (IOException e) {
//                }
//            }
//        }
//
//    }


    /**
     * 保存app异常崩溃的信息
     * @param ctx
     * @param str
     */
//    final static String CrashReport_NAME = "CrashReport";
//    public static void saveCrashReportInfo(Context ctx, String str){
////        saveInfo(ctx, str, "saveCrashReportInfo");
//
//        FileOutputStream fos = null;
//        try {
//            String path = Utils.getIntechStorageDir(ctx) + "/" + CrashReport_NAME;
//            File file = new File(path + "/" + CrashReport_NAME);
//            if (!file.exists())
//                file.mkdirs();
//            StringBuffer stringBuffer = new StringBuffer();
//            stringBuffer
//                    .append("VersionCode:" + Utils.getVersionCode(ctx))
//                    .append("---VersionName:" + Utils.getVersionName(ctx))
//                    .append("---Timer:")
//                    .append(Utils.getDate())
//                    .append(":")
//                    .append(str)
//                    .append("\r\n");
//            scanVideoFile(file.getAbsolutePath(), 1024*3);
//            File actionFile = new File(file.getAbsolutePath() + "/" + Utils.getDate2());
//            if (actionFile.exists() == false)
//                actionFile.createNewFile();
//            fos = new FileOutputStream(actionFile, true);
//            fos.write((stringBuffer.toString()).getBytes());
//            fos.flush();
//        } catch (Exception e) {
//        } finally {
//            if (fos != null) {
//                try {
//                    fos.close();
//                    fos = null;
//                } catch (IOException e) {
//                }
//            }
//        }
//
//    }

    /**
     * 保存信息到文件中
     *
     * @param ctx
     * @param str     信息
     * @param filName 文件名
     */
    public static void saveInfo(Context ctx, String str, String filName) {
        FileOutputStream fos = null;
        try {
            String path = Utils.getIntechStorageDir(ctx) + "/" + filName + "/";
            File dir = new File(path);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File file = new File(path + filName);
            if (!file.exists())
                file.createNewFile();
            if (file.length() > 1024 * 10) {// 大于10kb则自动删除
                file.delete();
                file.createNewFile();
            }
            fos = new FileOutputStream(file, true);
            fos.write((str + "\n").getBytes());
            fos.flush();
        } catch (Exception e) {
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                    fos = null;
                } catch (IOException e) {
                }
            }
        }
    }

    public static String getFileSuffix(byte[] bytes) {
        if (bytes == null || bytes.length < 10) {
            return null;
        }

        if (bytes[0] == 'G' && bytes[1] == 'I' && bytes[2] == 'F') {
            return "GIF";
        } else if (bytes[1] == 'P' && bytes[2] == 'N' && bytes[3] == 'G') {
            return "PNG";
        } else if (bytes[6] == 'J' && bytes[7] == 'F' && bytes[8] == 'I' && bytes[9] == 'F') {
            return "JPG";
        } else if (bytes[0] == 'B' && bytes[1] == 'M') {
            return "BMP";
        } else {
            return null;
        }
    }

    public static String getMimeType(byte[] bytes) {
        String suffix = getFileSuffix(bytes);
        String mimeType;

        if ("JPG".equals(suffix)) {
            mimeType = "image/jpeg";
        } else if ("GIF".equals(suffix)) {
            mimeType = "image/gif";
        } else if ("PNG".equals(suffix)) {
            mimeType = "image/png";
        } else if ("BMP".equals(suffix)) {
            mimeType = "image/bmp";
        } else {
            mimeType = "application/octet-stream";
        }

        return mimeType;
    }

    /**
     * 得到当前时间,格式如"2013-06-04 12:23:42"
     */
    public static String getDate() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return format.format(new Date());
    }

    /**
     * 得到当前时间,格式如"2013-06-04"
     */
    public static String getDate2() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(new Date());
    }

    /**
     * 当前时间比传入的时间大
     *
     * @param time 传入的时间，格式HH:mm
     * @return
     */
    public static boolean isLargerThan(String time) {
        if (time == null || time.isEmpty())
            return false;
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date date = df.parse(getDate2() + " " + time);
            if (date.getTime() < System.currentTimeMillis())
                return true;
            else
                return false;
        } catch (ParseException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 当前时间比传入的时间小
     *
     * @param time 传入的时间，格式HH:mm
     * @return
     */
    public static boolean isSmallerThan(String time) {
        if (time == null || time.isEmpty())
            return false;
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date date = df.parse(getDate2() + " " + time);
            if (date.getTime() > System.currentTimeMillis())
                return true;
            else
                return false;
        } catch (ParseException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 比较两个时间的大小，a比b大则返回0，a比b小则返回1，出错返回2，时间格式HH:mm:ss
     *
     * @param a
     * @param b
     * @return
     */
    public static int compare(String a, String b) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date dateA = df.parse(getDate2() + " " + a);
            Date dateB = df.parse(getDate2() + " " + b);
            if (dateA.getTime() > dateB.getTime())
                return 0;
            else
                return 1;
        } catch (ParseException e) {
            e.printStackTrace();
            return 2;
        }
    }

    /**
     * 將时间9:8:12格式化为HH:mm:ss格式09:08:12
     *
     * @param time
     * @return
     */
    public static String formatTime(String time) {
        if (time == null || time.isEmpty())
            return "";
        String[] strs = time.split(":");
        if (strs.length == 1) {
            return (strs[0].length() == 1 ? "0" + strs[0] : strs[0]) + ":00:00";
        } else if (strs.length == 2) {
            return (strs[0].length() == 1 ? "0" + strs[0] : strs[0]) + ":" +
                    (strs[1].length() == 1 ? "0" + strs[1] : strs[1]) + ":00";
        } else {
            return (strs[0].length() == 1 ? "0" + strs[0] : strs[0]) + ":" +
                    (strs[1].length() == 1 ? "0" + strs[1] : strs[1]) + ":" +
                    (strs[2].length() == 1 ? "0" + strs[2] : strs[2]);
        }
    }

    /**
     * 把全局变量序列化到本地
     */
    public static final void saveObject(String path, String fileName,
                                        Object saveObject) {
        FileOutputStream fos = null;
        ObjectOutputStream oos = null;

        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            File folder = new File(path);
            if (!folder.exists()) {
                folder.mkdirs();
            }
            File f = new File(folder, fileName);
            try {
                fos = new FileOutputStream(f);
                oos = new ObjectOutputStream(fos);
                oos.writeObject(saveObject);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (oos != null) {
                        oos.close();
                    }
                    if (fos != null) {
                        fos.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    /**
     * 反序列化
     */
    public static final Object restoreObject(String path) {
        FileInputStream fis = null;
        ObjectInputStream ois = null;
        Object object = null;
        File f = new File(path);
        if (!f.exists()) {
            return null;
        }
        try {
            fis = new FileInputStream(f);
            ois = new ObjectInputStream(fis);
            object = ois.readObject();
            return object;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                if (ois != null) {
                    ois.close();
                }
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return object;
    }

    //-----------------------------------------------------------------------------------------------------
//    private static void scanVideoFile(String videoFilePathStr, long maxFileSize) {
//        if (videoFilePathStr == null) {
//            return;
//        }
//        maxFileSize = maxFileSize * 1024;
//        if (maxFileSize <= 0){
//            maxFileSize = 10 * 1024;
//        }
//        File file = new File(videoFilePathStr);
//        if (!file.exists()) {
//            return;
//        }
//        try {
//            long fileSize = NESTSFileUtils.getFolderSize(file);
//            if (fileSize <= maxFileSize) {
//                return;
//            }
//            //按照创建时间升序排列，删除最旧的文件
//            File[] fileList = file.listFiles();
//            if (fileList == null) {
//                return;
//            } else {
//                for (File f : fileList) {
//                    long temp = NESTSFileUtils.getFolderSize(file);
//                    if (temp <= maxFileSize) {
//                        LogE("循环结束，不需要删除视频文件");
//                        break;
//                    }
//                    LogE("current video file size = " + temp);
//                    LogE(f.getName() + "start delate");
//                    f.delete();
//                }
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            return;
//        }
//    }



    private static void LogE(String str){
        Log.e("Utils", str);
    }



    /**
     * 获取版本号
     *
     * @return 当前应用的版本号
     */
    public static int getVersionCode(Context context) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            return info.versionCode;
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }

    /**
     * get App versionName
     * @param context
     * @return
     */
    public static String getVersionName(Context context){
        PackageManager packageManager=context.getPackageManager();
        PackageInfo packageInfo;
        String versionName="";
        try {
            packageInfo=packageManager.getPackageInfo(context.getPackageName(),0);
            versionName=packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionName;
    }


    //二进制转十六进制
    static String BinaryToHex(String s) {
        return Long.toHexString(Long.parseLong(s, 2));
    }

    //十六进制转二进制
    static String HexToBinary(String s) {
        return Long.toBinaryString(Long.parseLong(s, 16));
    }

}
